# leetcode 226 翻转二叉树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return root
        # 前序遍历
        root.left, root.right = root.right, root.left  # 交换左右节点
        self.invertTree(root.left)                     # 处理左子树
        self.invertTree(root.right)                    # 处理右子树
        return root

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return root
        # 后序遍历
        self.invertTree(root.left)                     # 处理左子树
        self.invertTree(root.right)                    # 处理右子树
        root.left, root.right = root.right, root.left  # 交换左右节点
        return root

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return root
        # 中序遍历
        self.invertTree(root.left)                     # 处理左子树
        root.left, root.right = root.right, root.left  # 交换左右节点
        self.invertTree(root.left)                    # 处理右子树(即交换后的左子树)
        return root


